package com.xy.etl.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.xy.core.annotation.RegisterServer;
import com.xy.etl.ds.model.DataSourceLog;
import com.xy.etl.kit.ClientHelper;
import com.xy.etl.kit.IEtlServer;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class ApplicationContextAware {
    //现场池
    private static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(50);

    @Value("${etl.log}")
    private String logLevel;

    @PostConstruct
    public void action() {
        //记录日志等级
        DataSourceLog.setLogLevel(logLevel);
        log.info("日志等级：" + logLevel);
        Map<String, IEtlServer> dataEtlMap;
        try {
            // 通过上下文，根据接口类型返回相应的所有实现类bean
            Map<String, IEtlServer> dataEtlMapTemp = SpringUtil.getBeansOfType(IEtlServer.class);
            if (dataEtlMapTemp == null || dataEtlMapTemp.size() == 0) {
                log.error("取得服务为空");
                return;
            }
            dataEtlMap = new HashMap<>();
            RegisterServer registerServer;
            String etlName;
            for (Map.Entry<String, IEtlServer> entry : dataEtlMapTemp.entrySet()) {
                registerServer = entry.getValue().getClass().getAnnotation(RegisterServer.class);
                if (registerServer == null) {
                    continue;
                }
                etlName = registerServer.value();
                if (etlName != null && etlName.length() >= 0) {
                    log.info("取得服务：" + entry.getValue());
                    dataEtlMap.put(etlName, entry.getValue());
                }
            }
        } catch (Exception ex) {
            log.error("取得服务异常：" + ex.getMessage(), ex);
            return;
        }

        for (IEtlServer server : dataEtlMap.values()) {
            log.info(server + " 启动服务类  " + server.getClass());
            scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
                @Override
                public void run() {
                    try {
                        String name = "[" + server.getClass().getSimpleName() + "] | [" + IdUtil.fastUUID().replace("-", "") + "]";
                        MDC.put("traceId", name);
                        log.info("");
                        log.info("************************************");
                        log.info("作业开始执行开始》》");
                        Long start = System.currentTimeMillis();
                        ClientHelper.setDefault(server.getClass().getSimpleName());
                        log.info("作业数据范围：" + ClientHelper.getDefault());
                        server.process();
                        log.info("作业开始执行结束《《   耗时：{}ms", (System.currentTimeMillis() - start));
                    } catch (Exception ex) {
                        log.error(server.getClass().getSimpleName() + " 作业执行异常" + ex.getMessage(), ex);
                    } finally {
                        log.info("************************************");
                        log.info("");
                        MDC.put("traceId", "");
                    }
                }
            }, 10, server.getIntervalSecond(), TimeUnit.SECONDS);
        }

    }

}
